﻿using EmailClient.Model;
using ServiceStack.OrmLite;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EmailClient.ViewModel
{
    class AttachmentViewModel
    {        
        // Summary:
        //     Get attachments of letter
        //
        // Parameters:
        //   letterId:
        //     Letter id.
        //
        // Exceptions:
        //   System.ArgumentNullException:
        //     The list parameter cannot be null.
        
        public static async Task<List<Attachment>> GetList(int letterId)
        {
            var dbFactory = new OrmLiteConnectionFactory(App.DBPath, SqliteDialect.Provider, false);
            using (var db = dbFactory.Open())
            {
                return await db.SelectAsync<Attachment>(x => x.LetterId == letterId);
            }
        }

        public static async Task<Attachment> Get(int letterId, int attId)
        {
            var dbFactory = new OrmLiteConnectionFactory(App.DBPath, SqliteDialect.Provider, false);
            using (var db = dbFactory.Open())
            {                
                var l = new List<Attachment>(await db.SelectAsync<Attachment>(x => x.LetterId == letterId && x.Id == attId));
                return l.First<Attachment>();
            }
        }

        public static async Task<Attachment> Insert(Attachment item)
        {
            var result = "success";
            try
            {
                var dbFactory = new OrmLiteConnectionFactory(App.DBPath, SqliteDialect.Provider, false);
                using (var db = dbFactory.Open())
                {
                    await db.InsertAsync(item);
                }
            }
            catch (Exception e) { result = e.Message; }

            return item;
        }

        public static async Task<string> DeleteAll(int letterId)
        {
            var result = "success";
            try
            {
                var dbFactory = new OrmLiteConnectionFactory(App.DBPath, SqliteDialect.Provider, false);
                using (var db = dbFactory.Open())
                {
                    await db.DeleteAsync<Attachment>(x => x.LetterId == letterId);
                }
            }
            catch (Exception e) { result = e.Message; }

            return result;
        }

    }
}
